
<template>
  <div class="resource-main-box  new-page">
    <a-form-model layout="inline" :model="search" class="comm-search-f" :style="`width: calc(100% - ${sideMenuWidth} - 33px)`">

      <!-- 筛选条件与查询 -->

      <a-form-model-item label="">
        <airModel v-model="search.model" width="100%" />
      </a-form-model-item>
      <!-- 目的地 -->
      <a-form-model-item label="">
        <a-select
          v-model="search.destination"
          show-arrow
          style="width: 100%!important;"
          placeholder="上行地址"
          allow-clear
        >
          <a-icon slot="suffixIcon" :component="require('@/assets/icon/arrow-down-bold.svg')" />
          <a-select-option v-for="selectItem in repUplinkDestinationF" :key="selectItem.id" :value="selectItem.title">
            {{ selectItem.title }}
          </a-select-option>
        </a-select>
      </a-form-model-item>
      <!-- 机队 -->
      <a-form-model-item label="">
        <a-select
          v-model="search.fleet"
          show-arrow
          style="width: 100%!important;"
          placeholder="机队"
          allow-clear
        >
          <a-icon slot="suffixIcon" :component="require('@/assets/icon/arrow-down-bold.svg')" />
          <a-select-option v-for="selectItem in ftmFleetList" :key="selectItem.id" :value="selectItem.name">
            {{ selectItem.name }}
          </a-select-option>
        </a-select>
      </a-form-model-item>
      <!-- 机型 -->

      <!-- 机号 -->
      <a-form-model-item label="">
        <tailNumber v-model="search.tailnumber" style="minWidth: 100%" value-key="tailnumber" name-key="tailnumber" mode="default" />
      </a-form-model-item>

      <!-- <a-form-model-item label="">
        <a-input
          v-model="search.code"
          placeholder="配置id"
        />
      </a-form-model-item> -->
      <!-- 事件名称 -->
      <a-form-model-item label="">
        <a-select
          v-model="search.event"
          show-arrow
          style="width: 100%!important;"
          placeholder="事件"
          allow-clear
        >
          <a-icon slot="suffixIcon" :component="require('@/assets/icon/arrow-down-bold.svg')" />
          <a-select-option v-for="selectItem in cmcEventList" :key="selectItem.id" :value="selectItem.name">
            {{ selectItem.name }}
          </a-select-option>
        </a-select>

      </a-form-model-item>
      <a-form-model-item label="">
        <a-input
          v-model="search.eventCode"
          placeholder="事件代码"
        />
        <!-- <eventCodeList v-model="search.code" value-key="value" mode="default"        style="minWidth: 100%" /> -->
      </a-form-model-item>
      <a-form-model-item label="">
        <a-select
          v-model="search.uplinkRequest"
          show-arrow
          style="minWidth: 100%"
          placeholder="上传报文请求"
          allow-clear
        >
          <a-icon slot="suffixIcon" :component="require('@/assets/icon/arrow-down-bold.svg')" />
          <a-select-option v-for="item in repUplinkRequest" :key="item.id" :value="item.name">
            {{ item.name }}
          </a-select-option>
        </a-select>

      </a-form-model-item>
      <a-form-model-item class="flex-1" style="max-width:100%!important">
        <a-button type="default" ghost :loading="repEventDrivenAcarsUplinkLoading" @click="resetSearchHandler">
          重置
        </a-button>
        <a-button type="primary" class="ml-8" :loading="repEventDrivenAcarsUplinkLoading" @click="changeTable({ current: 1 })">
          查询
        </a-button>

      </a-form-model-item>
    </a-form-model>

    <!-- table -->
    <div>
      <div class="pt-16 pl-16 pr-16 pb-16">
        <a-button type="primary" ghost :loading="repEventDrivenAcarsUplinkLoading" @click="addVisible=true">
          新增
        </a-button>
      </div>

      <a-table
        class="table-border"
        :columns="columns"
        size="middle"
        :data-source="repEventDrivenAcarsUplinkList"
        :row-key="(row,index) => row.id"
        :pagination="{
          showTotal:(total)=> `共 ${total} 条数据`,
          showSizeChanger: true,//设置每页显示数据条数
          showQuickJumper: true,
          size:'big',
          current:paginationOptions.pageNum,
          pageSize:paginationOptions.pageSize,
          total:paginationOptions.total
        }"
        :loading="repEventDrivenAcarsUplinkLoading"
        @change="changeTable"
      />

    </div>
    <!-- add -->
    <a-modal
      v-model="addVisible"
      :mask-closable="false"
      title=""
      :confirm-loading="addEventDrivenAcarsUplinkLoading"
      :width="400"
      class="rt-i-modal"
      :dialog-style="{height:'715px'}"
      @ok="addConfirmHandler"
      @cancel="cancelHandler"
    >
      <span slot="closeIcon" class="c-dialog-close-icon"><a-icon :component="require('@/assets/icon/close.svg')" /></span>

      <div class="c-dialog-title fw-500">{{ addTitle }}事件代码</div>

      <a-form-model
        ref="addForm"
        :model="addForm"
        :rules="addRules"
        layout="horizontal"
      >
        <a-form-model-item label="名称" prop="title">
          <a-input v-model="addForm.title" placeholder="名称" class="input-type-o" style="width: 100%" />
        </a-form-model-item>

        <a-form-model-item label="上行地址" prop="destination">

          <a-select
            v-model="addForm.destination"
            :show-arrow="false"
            style="width: 100%!important;"
            placeholder="上行地址"
            class="input-type-o"
            disabled
          >
            <a-icon slot="suffixIcon" :component="require('@/assets/icon/arrow-down-bold.svg')" />
            <a-select-option v-for="selectItem in repUplinkDestinationF" :key="selectItem.id" :value="selectItem.title">
              {{ selectItem.title }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="配置ID" prop="configurationId">
          <a-input
            v-model="addForm.configurationId"
            placeholder="配置ID"
            class="input-type-o"
          />

        </a-form-model-item>
        <!-- <a-form-model-item prop="fleet">
          <span slot="label">机队<span class="text-color-9ea5b2 fs-12">选填</span></span>
          <a-select
            v-model="addForm.fleet"
            show-arrow
            class="input-type-o"
            style="width:100%"
            placeholder="机队"
            allow-clear
          >
            <a-icon slot="suffixIcon" :component="require('@/assets/icon/arrow-down-bold.svg')" />
            <a-select-option v-for="selectItem in ftmFleetList" :key="selectItem.id" :value="selectItem.name">
              {{ selectItem.name }}
            </a-select-option>
          </a-select>
        </a-form-model-item> -->
        <a-form-model-item prop="tailnumber">
          <span slot="label">机号<span class="text-color-9ea5b2 fs-12">选填</span></span>
          <!-- <tailNumber

            class="input-type-o"
            value-key="tailnumber"
            name-key="tailnumber"
          /> -->
          <a-tree-select
            v-model="addForm.tailnumber"
            show-arrow
            placeholder="机号"
            class="input-type-o"
            dropdown-class-name="input-type-od tree-select-dbox"
            :tree-data="findListByFleetData"
            :replace-fields="{children:'children', title:'tailnumber', key:'id', value: 'tailnumber' }"
            :max-tag-count="2"
            tree-checkable
            allow-clear
          />

        </a-form-model-item>

        <a-form-model-item prop="model">
          <span slot="label">机型<span class="text-color-9ea5b2 fs-12">选填</span></span>
          <airModel v-model="addForm.model" class="input-type-o" />

        </a-form-model-item>

        <a-form-model-item label="上行模版" prop="uplinkRequest">
          <a-select
            v-model="addForm.uplinkRequest"
            show-arrow
            style="width: 100%"
            placeholder="上行模版"
            class="input-type-o"
            allow-clear
          >
            <a-icon slot="suffixIcon" :component="require('@/assets/icon/arrow-down-bold.svg')" />
            <a-select-option v-for="item in repUplinkRequest" :key="item.id" :value="item.name">
              {{ item.name }}
            </a-select-option>
          </a-select>

        </a-form-model-item>
        <a-form-model-item v-if="showMsg.smi==='ENG'" label="Modifier" prop="modifier">
          <a-select
            v-model="addForm.modifier"
            show-arrow
            style="width: 100%"
            class="input-type-o"
            placeholder="modifier"
            allow-clear
          >
            <a-icon slot="suffixIcon" :component="require('@/assets/icon/arrow-down-bold.svg')" />
            <a-select-option v-for="item in modifierArr" :key="item.name" :value="item.name">
              {{ item.name }}
            </a-select-option>
          </a-select>

        </a-form-model-item>
        <a-form-model-item label="事件" prop="event">
          <a-select
            v-model="addForm.event"
            show-arrow
            class="input-type-o"
            style="width: 100%!important;"
            placeholder="事件"
            allow-clear
          >
            <a-icon slot="suffixIcon" :component="require('@/assets/icon/arrow-down-bold.svg')" />
            <a-select-option v-for="selectItem in cmcEventList" :key="selectItem.id" :value="selectItem.name">
              {{ selectItem.name }}
            </a-select-option>
          </a-select>
        </a-form-model-item>

        <a-form-model-item prop="eventCode">
          <span slot="label">事件内容包含<span class="text-color-9ea5b2 fs-12">选填</span></span>
          <a-input v-model="addForm.eventCode" placeholder="事件内容包含" class="input-type-o" :min="0" style="width:100%" />
          <!-- <eventCodeList key="code" v-model="addForm.eventCode" class="input-type-o" value-key="value" mode="default" /> -->
        </a-form-model-item>
        <a-form-model-item label="Start Offset" prop="offset">
          <a-input-number v-model="addForm.offset" placeholder="Start Offset" class="input-type-o" :min="0" style="width:100%" />
        </a-form-model-item>
        <a-form-model-item label="Repetitive Interval" prop="repetitiveInterval">
          <a-input-number v-model="addForm.repetitiveInterval" placeholder="Repetitive Interval" class="input-type-o" :min="0" style="width:100%" />
        </a-form-model-item>
        <a-form-model-item label="最大上传次数" prop="maxUplink">

          <a-input-number v-model="addForm.maxUplink" class="input-type-o" :min="0" style="width:100%" />
        </a-form-model-item>

        <a-form-model-item label="消息内容">
          <a-textarea
            :value="messageFor"
            class="input-type-o"
            style="width: 100%"
            :auto-size="{ minRows: 5, maxRows: 8 }"
            disabled
          />
        </a-form-model-item>

      </a-form-model>
    </a-modal>
  </div>
</template>

<script>
import { mapState, mapActions, mapMutations, mapGetters } from 'vuex';
import rowClass from '@/pages/common/rowClass';
import { priorityList, modifierArr } from '@/pages/common/constant.js';
// import eventCodeList from '@/pages/components/eventCodeList';
// import eventList from '@/pages/components/eventList';
import tailNumber from '@/pages/components/tailNumber';
import airModel from '@/pages/components/airModel';
export default {
  components: {
    // eventCodeList,
    // eventList,
    tailNumber,
    airModel
  },
  mixins: [rowClass],
  data() {
    return {
      priorityList,
      modifierArr,
      search: {},
      sms: [
        {
          value: 0,
          name: '否'
        },
        {
          value: 1,
          name: '是'
        }
      ],
      addVisible: false,
      addForm: {},
      addTitle: '新增',
      columns: Object.freeze([
        {
          title: '名称',
          align: 'left',
          dataIndex: 'title',
          width: 200,
          customRender: (value, record) => {
            return [
              <div>{value || '--'}</div>,
              <div class='mt-4'><span>{record.createBy}</span> <span>{this.$moment.utc(record.updateTime).format('YYYY-MM-DD')}</span></div>
            ];
          }
        },
        {
          title: '机型',
          align: 'left',
          dataIndex: 'model',
          customRender: (value) => {
            return value || '--';
          }

        },
        {
          title: '配置ID',
          align: 'left',
          width: 80,
          dataIndex: 'configurationId',
          customRender: (value) => {
            return value || '--';
          }

        },
        {
          title: '机号',
          align: 'left',

          dataIndex: 'tailnumber',
          customRender: (value) => {
            const st = Object.prototype.toString.call(value) === '[object Array]' ? value.join() : value;
            return st || '--';
          }

        },
        {
          title: '事件',
          align: 'left',
          dataIndex: 'event',
          customRender: (value) => {
            return value || '--';
          }
        },
        {
          title: '触发选项',
          align: 'left',
          dataIndex: 'tt',
          width: 220,
          customRender: (value, record) => {
            return [
              <div>Code：{ record.eventCode }</div>,
              <div class='cfxx-text-box'>Start Offset：{ record.offset }</div>,
              <div class='cfxx-text-box'>Repeat Offset：{ record.repetitiveInterval }</div>,
              <div class='cfxx-text-box'>Max Repeat：{ record.maxUplink }</div>
            ];
          }

        },
        {
          title: '上行地址',
          align: 'left',
          width: 120,
          dataIndex: 'destination',
          customRender: (value) => {
            return value || '--';
          }
        },
        {
          title: '上行模板',
          align: 'left',
          width: 180,
          dataIndex: 'uplinkRequest',
          customRender: (value) => {
            return value || '--';
          }
        },
        {
          title: '样例',
          align: 'left',
          width: 180,
          dataIndex: 'exampleUplink',
          customRender: (value, record) => {
            return [<pre class='mb-0'>{record?.repUplinkRequest?.example ?? '--'}</pre>];
          }
        },
        {
          title: '冻结',
          align: 'left',
          width: 50,
          dataIndex: 'enable',
          customRender: (value, record) => {
            return [
              <a-switch size='small' checked={!value} onChange={() => this.enableHandler(record, 'enable')} >
                <a-icon slot='checkedChildren' type='check' style='font-size:10px'></a-icon>
              </a-switch>
            ];
          }
        },
        {
          title: '操作',
          align: 'left',
          dataIndex: 'op',
          width: 120,
          customRender: (value, record) => {
            return [
              <a-button type='link' onClick={() => this.editEventHandler(record)}>
                  编辑
              </a-button>,
              <a-popconfirm
                title='确认删除此项?'
                ok-type='danger'
                ok-text='确认'
                cancel-text='取消'
                onConfirm={() => this.delItemHandler(record)}
              >
                <a-button type='link' class='mr-5'>删除</a-button>
              </a-popconfirm>
            ];
          }

        }
      ]),
      addRules: Object.freeze({
        destination: [
          { required: true, message: '请填写', trigger: 'change' }
        ],
        event: [
          { required: true, message: '请填写', trigger: 'change' }
        ],
        configurationId: [
          { required: true, message: '请填写', trigger: 'change' }
        ],
        // eventCode: [
        //   { required: true, message: '请填写', trigger: 'change' }
        // ],
        // fleet: [
        //   { required: true, message: '请填写', trigger: 'change' }
        // ],
        // model: [
        //   { required: true, message: '请填写', trigger: 'change' }
        // ],
        // tailnumber: [
        //   { required: true, message: '请选择', trigger: 'change' }
        // ],
        maxUplink: [
          { required: true, message: '请选择', trigger: 'change' }
        ],
        message: [
          { required: true, message: '请选择', trigger: 'change' }
        ],
        title: [
          { required: true, message: '请选择', trigger: 'change' }
        ],
        uplinkRequest: [
          { required: true, message: '请选择', trigger: 'change' }
        ],
        repetitiveInterval: [
          { required: true, message: '请选择', trigger: 'change' }
        ],
        offset: [
          { required: true, message: '请选择', trigger: 'change' }
        ],
        modifier: [
          { required: true, message: '请选择', trigger: 'change' }
        ]

      })

    };
  },
  computed: {
    ...mapState('eventTriggerPacketUpload', [
      'addEventDrivenAcarsUplinkLoading',
      'repEventDrivenAcarsUplinkList',
      'repEventDrivenAcarsUplinkLoading',
      'paginationOptions',
      'cmcEventList',
      'findListByFleetData'
    ]),
    ...mapState('fraMonitoring', [
      'ftmFleetList',
      'repUplinkDestination',
      'repUplinkRequest'
    ]),
    repUplinkDestinationF() {
      const newData = JSON.parse(JSON.stringify(this.repUplinkDestination)).sort((a, b) => (a?.title ?? 0).localeCompare((b?.title ?? 0)));
      return newData;
    },
    messageFor() {
      const msg = this.repUplinkRequest.find(item => item.name === this.addForm?.uplinkRequest)?.example ?? '';
      const modifier = modifierArr.find(item => item.name === this.addForm?.modifier)?.format ?? '';

      if (this.showMsg.smi === 'ENG') {
        return msg + modifier;
      } else {
        return msg;
      }
    },
    ...mapGetters('setting', ['sideMenuWidth']),
    showMsg() {
      return this.repUplinkRequest.find(item => item.name === this.addForm?.uplinkRequest) ?? {};
    }
  },
  async mounted() {
    this.changeTable({ current: 1 });
    this.findListAllByFleet();
    this.getCmcEventList();
    await this.getUploadMessageConditions();
    this.$set(this.addForm, 'destination', 'Most Recent');
  },
  methods: {
    ...mapMutations('eventTriggerPacketUpload', [
      'setState'
    ]),
    ...mapActions('eventTriggerPacketUpload', [
      'getRepEventDrivenAcarsUplink',
      'addEventDrivenAcarsUplink',
      'updateRepEventDrivenAcarsUplink',
      'delRepEventDrivenAcarsUplink',
      'getCmcEventList',
      'findListAllByFleet'
    ]),
    ...mapActions('fraMonitoring', [
      'getUploadMessageConditions'

    ]),

    changeTable({ current, pageSize = 10 }) {
      if (pageSize !== this.paginationOptions.pageSize) {
        current = 1;
      }
      this.setState({ key: 'paginationOptions', payload: { ...this.paginationOptions, pageNum: current, pageSize }});
      this.getData();
    },
    enableHandler(record) {
      record.enable = (record.enable + 1) % 2;
      this.updateRepEventDrivenAcarsUplink(record).then((rep) => {
        if (rep) {
          this.addVisible = false;
          this.cancelHandler();
          this.getData();
        }
      });
    },
    addConfirmHandler() {
      this.$refs.addForm.validate(valid => {
        if (valid) {
          this.addForm.message = this.messageFor;
          this.addForm.exampleUplink = this.repUplinkRequest.find(item => item.name === this.addForm?.uplinkRequest)?.example ?? '';
          this.addForm.destinationId = this.repUplinkDestination.find(item => item.title === this.addForm?.destination)?.id ?? '';
          this.addForm.uplinkRequestId = this.repUplinkRequest.find(item => item.name === this.addForm?.uplinkRequest)?.id ?? '';
          this.addForm.uplinkContent = (this.messageFor.split('-')[1] ?? '').trim();
          (this.addForm?.tailnumber === '' || this.addForm?.tailnumber?.length === 0) ? this.addForm.tailnumber = null : '';
          if (this.addForm.id) {
            this.updateRepEventDrivenAcarsUplink(this.addForm).then((rep) => {
              if (rep) {
                this.addVisible = false;
                this.cancelHandler();
                this.getData();
              }
            });
          } else {
            this.addEventDrivenAcarsUplink(this.addForm).then((rep) => {
              if (rep) {
                this.addVisible = false;
                this.cancelHandler();
                this.changeTable({ current: 1 });
              }
            });
          }
        } else {
          return false;
        }
      });
    },
    cancelHandler() {
      this.addForm = {};
      this.addTitle = '新增';
      this.$refs.addForm.resetFields();
      this.$set(this.addForm, 'destination', 'Most Recent');
    },
    // 编辑
    editEventHandler(row) {
      this.addForm = { ...row };
      if (Object.prototype.toString.call(this.addForm.tailnumber) === '[object Null]') {
        this.addForm.tailnumber = [];
      }
      this.addVisible = true;
      this.addTitle = '修改';
    },
    // 确认删除
    delItemHandler({ id }) {
      this.delRepEventDrivenAcarsUplink({ id }).then((rep) => {
        if (rep) {
          this.getData();
        }
      });
    },
    // changeTailnumber() {
    //   const msg = this.repUplinkRequest.find(item => item.name === this.addForm?.uplinkRequest)?.message ?? '';
    //   this.addForm['message'] = this.addForm.tailnumber + '\n' + msg;
    // },
    // changeModifier(v) {
    //   const msg = this.repUplinkRequest.find(item => item.name === this.addForm?.uplinkRequest)?.message ?? '';

    //   const formatM = modifierArr.find(item => item.name === v).format;

    //   const tn = this.addForm.tailnumber ? this.addForm.tailnumber + '\n' : '';
    //   this.addForm['message'] = tn + msg + formatM;
    // },
    // 重置
    resetSearchHandler() {
      this.search = {};
      this.changeTable({ current: 1 });
    },
    // changeUplinkRequestHandler() {
    //   this.$set(this.addForm, 'modifier', undefined);
    //   const msg = this.repUplinkRequest.find(item => item.name === this.addForm?.uplinkRequest)?.message ?? '';
    //   this.addForm['message'] = this.addForm.tailnumber ? this.addForm.tailnumber + '\n' + msg : msg;
    // },
    getData() {
      this.getRepEventDrivenAcarsUplink(this.search);
    }
  }
};
</script>

<style lang="less">
@import 'index.less';
</style>
